package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
)

// localIP是网卡IP
func HTTPGet(url, localIP string) (*http.Response, error) {
	req, _ := http.NewRequest("GET", url, nil)
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				// localIP 网卡IP，":0" 表示端口自动选择
				lAddr, err := net.ResolveTCPAddr(netw, localIP+":0")
				if err != nil {
					return nil, err
				}

				rAddr, err := net.ResolveTCPAddr(netw, addr)
				if err != nil {
					return nil, err
				}
				conn, err := net.DialTCP(netw, lAddr, rAddr)
				if err != nil {
					return nil, err
				}
				return conn, nil
			},
		},
	}

	return client.Do(req)
}

func main() {
	// 获取本机的所有网络接口
	interfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// 遍历每个网络接口
	for _, inter := range interfaces {
		fmt.Printf("Interface Name: %s\n", inter.Name)
		fmt.Printf("Interface MAC: %s\n", inter.HardwareAddr)
		fmt.Printf("Interface IPs:\n")

		// 获取每个接口的所有IP地址
		addrs, err := inter.Addrs()
		if err != nil {
			fmt.Println(err)
			continue
		}

		// 遍历每个IP地址
		for _, addr := range addrs {
			fmt.Printf("- %s\n", addr.String())
		}
	}

	res, err := HTTPGet("http://localhost:8080/ping", "10.10.100.106")
	if err != nil {
		//
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		// handle error
	}

	fmt.Println(string(body))
}
